package com.eobard.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.AES;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: Eobard Gu
 * @Date: 2025-08-05
 * @Description: 环境检查工具类
 */
public class EnvUtils {

    //运行指定command命令
    public static void run(String command) {
        checkEnv(command);
    }

    //检查当前电脑是否有command的环境
    public static void checkEnv(String command) {
        checkEnv(List.of(command.split(" ")));
    }

    //检查当前电脑是否有command的环境
    public static void checkEnv(List<String> command) {
        try {
            // 启动进程执行命令
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            Process process = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            int exitCode = process.waitFor();
            reader.close();
            if (exitCode != 0) {
                throw new RuntimeException("命令执行失败: " + String.join(" ", command) + "\n输出:\n" + output);
            }
        } catch (IOException e) {
            throw new RuntimeException("未找到命令: " + String.join(" ", command), e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("执行命令被中断: " + String.join(" ", command), e);
        }
    }


    //检查当前电脑是否下载了具体的python依赖
    public static void hasPythonDependencies(List<String> dependencies) {
        try {
            // 执行命令：pip list
            ProcessBuilder builder = new ProcessBuilder("pip3", "list");
            builder.redirectErrorStream(true);
            Process process = builder.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            Set<String> installedPackages = new HashSet<>();
            String line;
            boolean readingPackages = false;
            while ((line = reader.readLine()) != null) {
                if (!readingPackages) {
                    if (line.startsWith("---")) {
                        readingPackages = true;
                    }
                    continue;
                }
                String[] parts = line.trim().split("\\s+");
                if (parts.length >= 1) {
                    installedPackages.add(parts[0].toLowerCase());
                }
            }

            process.waitFor();
            reader.close();

            boolean allMatch = dependencies.stream()
                    .filter(dep -> StrUtil.isNotBlank(dep))
                    .map(String::toLowerCase)
                    .allMatch(installedPackages::contains);

            if (!allMatch) {
                throw new RuntimeException("请先下载相关依赖: " + dependencies);
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("检查 Python 依赖时出错: " + e.getMessage(), e);
        }
    }

    //检查当前电脑是否存在python环境
    public static void isPythonAvailable(String explainer) {
        try {
            ProcessBuilder checkBuilder = new ProcessBuilder(explainer, "--version");
            checkBuilder.redirectErrorStream(true);
            Process process = checkBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String output = reader.readLine();
            process.waitFor();
            reader.close();
            boolean exist = output != null && output.toLowerCase().contains("python");
            if (!exist) {
                throw new RuntimeException("当前系统并未安装 Python 解释器:" + explainer);
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static String decrypt(String encrypted) {
        return new AES("+lxeNXHOJHfos3iFO8brwg==".getBytes()).decryptStr(Base64.decode(encrypted));
    }
}
